import { _decorator, director, error, sys } from 'cc';
const { ccclass, property } = _decorator;

const isKSGame = typeof window['KSGameGlobal'] != 'undefined';

@ccclass('AdMgr')
export default class AdMgr {
    private static _ins: AdMgr;
    public static get Instance() { return this._ins ?? (this._ins = new AdMgr); }
    private static VideoIdOnTt = '6c50dc9b9bm96g62h3';
    private static VideoIdOnWx = '';
    private static InterIdOnWx = '';
    private static GridIdOnWx = '';
    private static VideoIdOnOppo = '';
    private static VideoIdOnVivo = '';
    private static VideoIdOnKs = '2300011609_01';
    private static VideoIdOnMy = '';
    private _videoAd: any;
    private _gridAd: any;
    constructor() {
        if (window['tt']) {
            this._videoAd = tt.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnTt });
            this._gridAd = tt.createGridGamePanel({ gridCount: 'one' });
        } else if (isKSGame) {
            this._videoAd = ks.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnKs });
        } else if (window['wx']) {
            this._videoAd = wx.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnWx });
            this._videoAd.onError((errMsg: string, errCode: number) => error(errMsg));
            this._gridAd = wx.createCustomAd({
                adUnitId: AdMgr.GridIdOnWx,
                style: {
                    left: wx.getSystemInfoSync().screenWidth / 2 - 180 * .8,
                    top: wx.getSystemInfoSync().screenHeight - 106 * .8,
                },
                adIntervals: 30
            });
        } else if (window['qg'] && sys.platform == sys.Platform.OPPO_MINI_GAME) {
            this._videoAd = qg.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnOppo });
        } else if (window['qg'] && sys.platform == sys.Platform.VIVO_MINI_GAME) {
            this._videoAd = qg.createRewardedVideoAd({ posId: AdMgr.VideoIdOnVivo });
        } else if (sys.platform == sys.Platform.ALIPAY_MINI_GAME) {
            this._videoAd = my.createRewardedAd({ adUnitId: AdMgr.VideoIdOnMy });
        }
    }
    async showVideoAd(): Promise<boolean> {
        if (window['tt']) {
            if (localStorage.getItem('gift_ad_free')) {
                localStorage.removeItem('gift_ad_free');
                return true;
            }

            const { query } = tt.getLaunchOptionsSync();
            if (!this._videoAd) this._videoAd = tt.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnTt });
            const videoAd: any = this._videoAd;
            await videoAd.load();
            await videoAd.show();
            const { isEnded, count } = await new Promise<{ isEnded: boolean, count: boolean }>((resolve) => videoAd.onClose(resolve));
            if (count) {
                const { query } = tt.getLaunchOptionsSync();
            }
            return count;
        } else if (isKSGame) {
            if (!this._videoAd) this._videoAd = ks.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnKs });
            const videoAd = this._videoAd;
            await videoAd.show();
            const { isEnded } = await new Promise<{ isEnded: boolean }>(resolve => videoAd.onClose(resolve));
            return isEnded;
        } else if (window['wx']) {
            if (!this._videoAd) this._videoAd = wx.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnWx });
            const videoAd = this._videoAd;
            await videoAd.load();
            await videoAd.show();
            const { isEnded } = await new Promise<{ isEnded: boolean }>(resolve => videoAd.onClose(resolve));
            return isEnded;
        } else if (window['qg'] && sys.platform == sys.Platform.OPPO_MINI_GAME) {
            if (!this._videoAd) this._videoAd = qg.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnOppo });
            const videoAd = this._videoAd;
            await videoAd.load();
            await videoAd.show();
            const { isEnded } = await new Promise<{ isEnded: boolean }>(resolve => videoAd.onClose(resolve));
            return isEnded;
        } else if (window['qg'] && sys.platform == sys.Platform.VIVO_MINI_GAME) {
            if (!this._videoAd) this._videoAd = qg.createRewardedVideoAd({ posId: AdMgr.VideoIdOnVivo });
            const videoAd = this._videoAd;
            await videoAd.load();
            await videoAd.show();
            const { isEnded } = await new Promise<{ isEnded: boolean }>(resolve => videoAd.onClose(resolve));
            return isEnded;
        } else if (sys.platform == sys.Platform.ALIPAY_MINI_GAME) {
            if (!this._videoAd) this._videoAd = my.createRewardedAd({ adUnitId: AdMgr.VideoIdOnMy });
            const viewoAd = this._videoAd;
            viewoAd.onError(res => {
                console.log('错误码', res.error);
                console.log('错误消息', res.errorMessage);
            });
            try {
                await viewoAd.load();
                await viewoAd.show();
            } catch (err) {
                console.error(err);
            }
            const { isEnded } = await new Promise<{ isEnded: boolean }>((resolve, reject) => viewoAd.onClose(resolve));
            return isEnded;
        } else if (sys.isNative && sys.os == sys.OS.IOS) {
            const promise = new Promise<boolean>(res => director.once('event:rewarded_videoAd', () => res(true)));
            // @ts-ignore
            jsb.reflection.callStaticMethod('AdApi', 'ShowRewardVideoAd');
            return await promise;
        } else if (window['h5api']) {
            await new Promise<void>((res, rej) => {
                window['h5api'].playAd(({ code, message }: { code: number, message: string }) => {
                    if (code === 10000) {
                        // 开始播放
                    } else if (code === 10001) {
                        res();
                    } else {
                        rej(new Error('广告异常'));
                    }
                });
            });
            return true;
        } else {
            return true;
        }
    }

    async showMultiVideoAd(rewardMsg: string[], times: number, progressTip: boolean) {
        // if (window['tt']) {
        // const sysInfo = tt.getSystemInfoSync();
        // if (sysInfo.platform == 'android' && (sysInfo.appName == 'Douyin' || sysInfo.appName == 'douyin_lite')) {
        // const { query } = tt.getLaunchOptionsSync();
        // let videoAd = this._videoAd;
        // if (videoAd) await videoAd.destroy();
        // videoAd = this._videoAd = tt.createRewardedVideoAd({ adUnitId: AdMgr.VideoIdOnTt, multiton: true, multitonRewardMsg: rewardMsg, multitonRewardTimes: times, progressTip });
        // await videoAd.load();
        // await videoAd.show();
        // const { count } = await new Promise<{ count: number }>(resolve => videoAd.onClose(resolve));
        // videoAd.destroy().then(() => this._videoAd = null);
        // if (count) {
        // const { query } = tt.getLaunchOptionsSync();
        // }
        // return count;
        // } else {
        // return await this.showVideoAd() ? 1 : 0;
        // }
        // } else {
        // return await this.showVideoAd() ? 1 : 0;
        // }
    }
    async showInterAd() {
        // if (window['wx']) {
        // const interAd = wx.createInterstitialAd({ adUnitId: AdMgr.InterIdOnWx });
        // await interAd.load();
        // await interAd.show();
        // }
    }
    async showGridAd() {
        // if (!this._gridAd) return;
        // if (window['wx']) {
        // (this._gridAd as wx.CustomAd).show();
        // } else if (window['tt']) {
        // this._gridAd.show();
        // }
    }
    hidGridAd() {
        // if (!this._gridAd) return;
        // if (window['wx']) {
        // (this._gridAd as wx.CustomAd).hide();
        // } else if (window['tt']) {
        // this._gridAd.hide();
        // }
    }
}